import React, { useState, memo, useEffect } from 'react';
import { Table, Button, Row } from 'tdesign-react';
import SearchForm from './components/SearchForm';

import classnames from 'classnames';
import CommonStyle from '@/styles/common.module.less';
import { useNavigate, useLocation } from 'react-router-dom';
import PubSub from 'pubsub-js'
import { getReservationListAPI } from '@/api/reservation.api';
import dayjs from 'dayjs';

import './index.module.less';

type AlignType = 'left' | 'center' | 'right';
type FixedType = 'left' | 'right';

const statusColorMap: Record<string, React.ReactNode> = {
  approved: <span style={{ color: '#52c41a' }}>已审批</span>,
  pending: <span style={{ color: '#faad14' }}>待审批</span>,
  rejected: <span style={{ color: '#f5222d' }}>已拒绝</span>,
};

export const SelectTable = () => {
  // 获取当前路由地址
  const location = useLocation();
  const listPath = location.pathname.split('/').pop();
  // pub-sub 发布当前的路由
  PubSub.publish('listPath', listPath);
  const [reservationList, setReservationList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const navgate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);

  // 搜索和排序参数state
  const [searchParams, setSearchParams] = useState({
    page: 1,
    pageSize: 3,
    searchText: '',
    status: '',
    sortBy: 'studentId',
    sortOrder: 'ASC',
  });

  // 搜索表单提交
  const handleSearch = (values: any) => {
    let name = '';
    let studentId = '';
    if (values.searchText) {
      if (/^\d+$/.test(values.searchText)) {
        studentId = values.searchText;
      } else {
        name = values.searchText;
      }
    }
    setSearchParams(prev => ({
      ...prev,
      ...values,
      name,
      studentId,
      page: 1, // 搜索时重置到第一页
    }));
  };

  // 排序、分页、筛选联动
  useEffect(() => {
    setLoading(true);
    getReservationListAPI({
      page: searchParams.page,
      pageSize: searchParams.pageSize,
      sortBy: searchParams.sortBy,
      sortOrder: searchParams.sortOrder,
      status: searchParams.status,
      searchText: searchParams.searchText,
    }).then(res => {
      const data = res.data.data;
      const reservations = data.list || [];
      setReservationList(reservations.map((item: any) => ({
        id: item.id,
        studentId: item.user?.studentId || '',
        name: item.user?.name || '',
        email: item.user?.email || '',
        roomNumber: item.room?.roomNumber || '',
        floor: item.room?.floor?.floorNumber || '',
        startTime: item.startTime,
        endTime: item.endTime,
        status: item.status,
        purpose: item.purpose,
        duration: item.duration,
      })));

      setTotal(data.total || 0);
    }).finally(() => setLoading(false));
  }, [searchParams]);

  // 分页事件
  const handlePageChange = (current: number, pageInfo: any) => {
    setSearchParams(prev => ({
      ...prev,
      page: pageInfo.current,
      pageSize: pageInfo.pageSize,
    }));
  };
  // 排序事件
  const handleSortChange = (sort: any) => {
    if (sort && sort.length > 0) {
      setSearchParams(prev => ({
        ...prev,
        sortBy: sort[0].sortBy,
        sortOrder: sort[0].desc ? 'DESC' : 'ASC',
      }));
    }
  };

  // 选择
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  // 重新处理点击操作
  function rehandleClickOp(record: any) {
    navgate(`/room/approve?id=${record.row.id}`);
  }

  // 用户管理表格列
  const reservationColumns = [
    {
      title: '学号',
      align: 'left' as AlignType,
      width: 120,
      colKey: 'studentId',
    },
    {
      title: '姓名',
      align: 'left' as AlignType,
      width: 100,
      colKey: 'name',
    },
    {
      title: '楼层',
      align: 'center' as AlignType,
      width: 80,
      colKey: 'floor',
    },
    {
      title: '包间号',
      align: 'center' as AlignType,
      width: 100,
      colKey: 'roomNumber',
    },
    {
      title: '起止时间',
      align: 'center' as AlignType,
      width: 220,
      colKey: 'timeRange',
      cell({ row }: any) {
        // 只显示年月日
        const start = row.startTime ? dayjs(row.startTime).format('YYYY-MM-DD') : '';
        const end = row.endTime ? dayjs(row.endTime).format('YYYY-MM-DD') : '';
        return `${start} ~ ${end}`;
      },
    },
    {
      title: '共计天数',
      align: 'center' as AlignType,
      width: 120,
      colKey: 'duration',
    },
    {
      title: '用途',
      align: 'left' as AlignType,
      width: 120,
      colKey: 'purpose',
    },
    {
      title: '状态',
      align: 'center' as AlignType,
      width: 100,
      colKey: 'status',
      cell({ row }: any) {
        return statusColorMap[row.status] || row.status;
      },
    },
    {
      align: 'center' as AlignType,
      fixed: 'right' as FixedType,
      width: 180,
      colKey: 'op',
      title: '操作',
      cell(record: any) {
        return (
          <>
            <Button
              theme='primary'
              variant='text'
              disabled={record.row.status !== 'pending'}
              onClick={() => {
                rehandleClickOp(record);
              }}
            >审批</Button>
          </>
        );
      },
    },
  ];
  return (
    <>
      <Row justify='start' style={{ marginBottom: '20px' }}>
        <SearchForm
          onSubmit={handleSearch}
          onCancel={() => setSearchParams({ ...searchParams })}
        />
      </Row>
      <Table
        loading={loading}
        data={reservationList}
        columns={reservationColumns}
        rowKey='id'
        selectedRowKeys={selectedRowKeys}
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: searchParams.pageSize,
          total,
          current: searchParams.page,
          showJumper: true,
          pageSizeOptions: [3, 5, 8, 10],
          onCurrentChange: handlePageChange,
          onPageSizeChange: (size) => handlePageChange(1, { current: 1, pageSize: size }),
        }}
        sort={{
          sortBy: searchParams.sortBy,
          descending: searchParams.sortOrder === 'DESC',
        }}
        onSortChange={handleSortChange}
      />
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
